package com.iyao_app.im.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.iyao_app.Friends.LQRAdapterForRecyclerView;
import com.iyao_app.Friends.LQRViewHolderForRecyclerView;
import com.iyao_app.R;
import com.iyao_app.base.BaseActivityWithHead;
import com.iyao_app.im.imageloader.ImageLoaderManager;
import com.iyao_app.im.model.Contact;
import com.iyao_app.im.nimsdk.NimFriendSDK;
import com.iyao_app.im.nimsdk.NimRecentContactSDK;
import com.iyao_app.im.nimsdk.NimUserInfoSDK;
import com.iyao_app.im.nimsdk.utils.NimTeamSDK;
import com.iyao_app.im.nimsdk.utils.TimeUtils;
import com.iyao_app.util.ResourcesUtils;
import com.iyaowoqu.base_library.util.LogUtil;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.ResponseCode;
import com.netease.nimlib.sdk.friend.model.Friend;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.RecentContact;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MessageListActivity extends BaseActivityWithHead {


    private List<RecentContact> mRecentContactList = new ArrayList<>();//最近联系人列表

    private LQRAdapterForRecyclerView<RecentContact> mAdapter;

    @BindView(R.id.cvMessage)
    RecyclerView mCvMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_list);
        ButterKnife.bind(this);
        init();
        initData();
    }

    public void init() {
        setTitleTV(ResourcesUtils.getString(R.string.message));
        //监听最近联系人
//        observeRecentContact();

        //最近会话列表
        observeHuiHua();
    }

    public void initData() {
        getLocalRecentData();
    }


    private void setAdapter() {
        mAdapter = new LQRAdapterForRecyclerView<RecentContact>(this, R.layout.list_item_conversation, mRecentContactList) {
            @Override
            public void convert(final LQRViewHolderForRecyclerView helper, final RecentContact item, int position) {
                final ImageView ivHeader = helper.getView(R.id.iv_avatar);//单聊头像
                if (item.getSessionType() == SessionTypeEnum.P2P) {
                    ivHeader.setVisibility(View.VISIBLE);
                    //设置条目的常规信息
                    Friend friend = NimFriendSDK.getFriendByAccount(item.getContactId());
                    NimUserInfo userInfo = NimUserInfoSDK.getUser(item.getContactId());
                    if (userInfo == null) {
                        return;
                    }
                    Contact contact = new Contact(friend, userInfo);

                    //设置单聊的头像
                    if (userInfo != null && !TextUtils.isEmpty(userInfo.getAvatar())) {
                        ImageLoaderManager.LoadNetImage(userInfo.getAvatar(), ivHeader);
                    } else {
                        (ivHeader).setImageResource(R.mipmap.ic_guanlogo);
                    }

                    helper.setText(R.id.tv_username, contact.getDisplayName());
                } else {

                }

                helper.setText(R.id.tv_msg, item.getContent())
                        .setText(R.id.tvTime, TimeUtils.getMsgFormatTime(item.getTime()));
                //  MoonUtil.identifyFaceExpressionAndTags(this, helper.getView(R.id.tv_msg), item.getContent(), ImageSpan.ALIGN_BOTTOM, 0.45f);

                //判断是否有未读消息
                helper.setViewVisibility(R.id.tvUnread, item.getUnreadCount() > 0 ? View.VISIBLE : View.GONE).setText(R.id.tvUnread, String.valueOf(item.getUnreadCount()));

                //条目点击跳转至聊天界面
                helper.getView(R.id.root).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(MessageListActivity.this, SessionActivity.class);
                        intent.putExtra(SessionActivity.SESSION_ACCOUNT, item.getContactId());
                        intent.putExtra(SessionActivity.SESSION_TYPE, item.getSessionType());
                        startActivity(intent);
                        //清空当前联系人的未读数
                        NimRecentContactSDK.clearUnreadCount(item.getContactId(), item.getSessionType());
                    }
                });
            }
        };
        mCvMessage.setAdapter(mAdapter);
    }

    /**
     * 加载本地联系人信息
     */
    private void getLocalRecentData() {
        //获取最近联系人
        NimRecentContactSDK.queryRecentContacts(new RequestCallbackWrapper<List<RecentContact>>() {
            @Override
            public void onResult(int code, List<RecentContact> result, Throwable exception) {
                if (code != ResponseCode.RES_SUCCESS || exception != null)
                    return;

                //如果我已经不是最近聊天中的群聊的成员，则不显示这个最近群聊项
                for (int i = 0; i < result.size(); i++) {
                    RecentContact rc = result.get(i);
                    if (rc.getSessionType() == SessionTypeEnum.Team) {
                        if (!NimTeamSDK.queryTeamBlock(rc.getContactId()).isMyTeam()) {
                            result.remove(i);
                            NimRecentContactSDK.deleteRecentContact(rc);
                            i--;
                        }
                    }
                }

                mRecentContactList.clear();
                mRecentContactList.addAll(result);
                setAdapter();

                updateRecentContactInfoFromServer();

            }
        });
    }

    /**
     * 更新最近联系人的本地信息
     */
    private void updateRecentContactInfoFromServer() {
        if (mRecentContactList != null && mRecentContactList.size() > 0) {
            List<String> accounts = new ArrayList<>();
            for (RecentContact rc : mRecentContactList) {
                accounts.add(rc.getFromAccount());
            }
            if (accounts != null && accounts.size() > 0) {
                NimUserInfoSDK.getUserInfosFormServer(accounts, new RequestCallback<List<NimUserInfo>>() {
                    @Override
                    public void onSuccess(List<NimUserInfo> param) {
                        setAdapter();
                    }

                    @Override
                    public void onFailed(int code) {

                    }

                    @Override
                    public void onException(Throwable exception) {

                    }
                });
            }
        }
    }

    /**
     * 监听最近联系人
     */
    private void observeHuiHua() {
        NIMClient.getService(MsgService.class).queryRecentContacts()
                .setCallback(new RequestCallbackWrapper<List<RecentContact>>() {
                    @Override
                    public void onResult(int code, List<RecentContact> recents, Throwable e) {
                        // recents参数即为最近联系人列表（最近会话列表）
                        LogUtil.e("recents","recents" + recents.get(0).getContactId());

                        if (recents != null && recents.size() > 0) {
                            if (mAdapter != null) {
                                int index;
                                for (RecentContact r : recents) {
                                    index = -1;
                                    for (int i = 0; i < mAdapter.getData().size(); i++) {
                                        if (r.getContactId().equals(mAdapter.getData().get(i).getContactId())
                                                && r.getSessionType() == (mAdapter.getData().get(i).getSessionType())) {
                                            index = i;
                                            break;
                                        }
                                    }
                                    if (index >= 0) {
                                        mAdapter.removeItem(index);
                                    }
                                    mAdapter.addFirstItem(r);
                                }
                            }
                        }
                    }
                });
//        NimRecentContactSDK.observeRecentContact(mMessageObserver, true);
    }

    @OnClick({R.id.rl_attention_message, R.id.rl_system_message})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_attention_message:
                break;
            case R.id.rl_system_message:
                break;
        }
    }
}
